package com.example.cmpe277stockdata;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import com.example.cmpe277stockdata.RSSFeeds.NewsReader;
import com.example.cmpe277stockdata.RSSFeeds.RealTimeRSSFeed;
import com.example.cmpe277stockdata.RSSFeeds.ResultClass;
import com.example.cmpe277stockdata.beans.NewsBean;
import com.example.cmpe277stockdata.beans.RealTimeBean;
import com.example.cmpe277stockdata.beans.UserBean;
import com.example.cmpe277stockdata.beans.UserPortfolio;
import com.example.cmpe277stockdata.constants.DataConstants;
import com.example.cmpe277stockdata.dataaccess.AzureLogin;
import com.example.cmpe277stockdata.dataaccess.AzurePortfolio;
import com.example.cmpe277stockdata.dataaccess.PortFolioDB;
import com.microsoft.windowsazure.mobileservices.MobileServiceClient;
import com.microsoft.windowsazure.mobileservices.MobileServiceTable;
import com.microsoft.windowsazure.mobileservices.ServiceFilterResponse;
import com.microsoft.windowsazure.mobileservices.TableQueryCallback;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

public class LandingActivity extends Activity 
{
	/*NewsReader reader = new NewsReader();
	private Intent intent;*/
	
	private Context ctx;
	private UserBean userData = null;
	/*private List<RealTimeBean> result = null;
	private String companyName;
	private TextView headerView;*/
	private ListView listviewRealTime;
	public ArrayList<RealTimeBean> realTimeData;
	AzurePortfolio portfolioazure;
	private MobileServiceClient mClient;
	List<UserPortfolio> result =  new ArrayList<UserPortfolio>();;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_landing);
        
        userData = (UserBean) getIntent().getSerializableExtra(DataConstants.USER_DATA);
        
        ctx=this;
        if(userData != null)
        {
        	//User Logged In 
        	TextView txtLogin = (TextView) findViewById(R.id.txtLogin);
        	txtLogin.setText("Hi " + userData.getUserName());
        	
        	TextView txtLogout =(TextView) findViewById(R.id.txtLogOut);
        	txtLogout.setVisibility(View.VISIBLE); 
        	this.getPortFolioList(userData.getId());	
        }
        else
        {
        	TextView txtLogout =(TextView) findViewById(R.id.txtLogOut);
        	txtLogout.setVisibility(View.INVISIBLE);
        	RealTimeData realTimeData = new RealTimeData();
            realTimeData.execute();
        }
       
        
//        RealTimeData realTimeData = new RealTimeData();
//        realTimeData.execute();		
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.landing, menu);
        return true;
    }
    
    
    public class RealTimeData extends AsyncTask<String, Void, ArrayList<RealTimeBean>>
    {		
    	
		@Override
		protected void onPostExecute(ArrayList<RealTimeBean> result) 
		{
			realTimeData = result;
						
			listviewRealTime = (ListView) findViewById(R.id.lstRealTimeData);
			
			RealTimeAdapter adapter =  new RealTimeAdapter(ctx, R.layout.real_time_data, realTimeData);
			adapter.setUserData(userData);
			
			listviewRealTime.setAdapter( adapter);
		}

		@Override
		protected ArrayList<RealTimeBean> doInBackground(String... arg0) 
		{
			RealTimeRSSFeed read= new RealTimeRSSFeed();
			ArrayList<RealTimeBean> result = new ArrayList<RealTimeBean>();
			//PortFolioDB db = new PortFolioDB(ctx);
			
			for(int i=0;i< ResultClass.tickerarray.length;i++)
			{
				String[] tickerexpansion = ResultClass.tickerarray[i].split(":");
				try
				{
					RealTimeBean data = new RealTimeBean();
					data = read.getRealTimeRate(tickerexpansion[0],tickerexpansion[1]);
					result.add(data);
				}
				catch(Exception e)
				{
					System.out.println(e.getMessage());
				}
			}
			
			if(userData != null)
			{
				/*db.open();
				List<UserPortfolio> list = db.getPortFolioList(userData.getId());
				db.close();*/
				try {
					portfolioazure = new AzurePortfolio(getApplicationContext());
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				List<UserPortfolio> list = DataConstants.userSelection;
				
				for(int j=0;j<result.size();j++)
				{
					for(int i= 0;i< list.size();i++)
					{
						if(result.get(j).getTickerSymbol().equalsIgnoreCase(list.get(i).getTickerSymbol()))
							result.get(j).setSelected(true);
					}
				}
			}
			
			return result;
		}
    	
    }
    
    public List<UserPortfolio> getPortFolioList(int userId)
	{
    	try {
			mClient = new MobileServiceClient(
					"https://stockdata.azure-mobile.net/",
					"gbRGSggWlHFQwsQmeMgEULUirbGHgk27", ctx);
		
		
		MobileServiceTable<UserPortfolio> table = mClient.getTable("UserPortfolio", UserPortfolio.class);
		table.where().field("userId").eq(String.valueOf(userId)).execute(new TableQueryCallback<UserPortfolio>() {

			@Override
			public void onCompleted(
					List<UserPortfolio> checkeduser,
					int arg1,
					Exception exception,
					ServiceFilterResponse arg3) {
				if (exception == null) {
					if(checkeduser == null || checkeduser.size() < 1)
					{
						DataConstants.IS_AZURE_ACTION_COMPLETE = true;
						RealTimeData realTimeData = new RealTimeData();
				        realTimeData.execute();	
					}
					else
					{
						DataConstants.IS_AZURE_ACTION_COMPLETE = true;
						for(UserPortfolio portfolio : checkeduser)
						{
							UserPortfolio data = new UserPortfolio();
							data.setCompanyName(portfolio.getCompanyName());
							data.setTickerSymbol(portfolio.getTickerSymbol());
							data.setUserName(portfolio.getUserName());
							data.setUserId(portfolio.getId());
							data.setTableId(portfolio.getTableId());
							result.add(data);
						}
						DataConstants.userSelection = result;
						RealTimeData realTimeData = new RealTimeData();
				        realTimeData.execute();	

					}

				} else {
					DataConstants.IS_AZURE_ACTION_COMPLETE = true;
					RealTimeData realTimeData = new RealTimeData();
			        realTimeData.execute();	
				}


			}
		});

    	} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
		
	}
	
    public void onLogin(View view)
    {
    	Intent intent = new Intent(this,MainActivity.class);
    	startActivity(intent);
    }
   
    public void onLogout(View view)
    {
    	if(userData != null)
    	{
    		userData = null;
    		TextView txtLogin = (TextView) findViewById(R.id.txtLogin);
        	txtLogin.setText(R.string.login);
        	TextView txtLogout = (TextView) findViewById(R.id.txtLogOut);
        	txtLogout.setVisibility(View.INVISIBLE);
        	RealTimeData realTimeData = new RealTimeData();
            realTimeData.execute();
    	}
    		
    	
    }
    
  }
